package Beginner_Algorithm;

public class Adding_two_linked_lists {
    public static class node {
        int sum;
        node next;

        public node(int i) {
            sum = i;
        }
        private node() {

        }
    }

    public static void print(node node) {
        while (node != null) {
            System.out.print(node.sum);
            node = node.next;
        }
    }

    public static node AddTowNumber(node one, node tow) {
        node l = countLength(one) > countLength(tow) ? one : tow;
        node s = countLength(one) > countLength(tow) ? tow : one;
        node curl = l;
        node curs = s;
        node last = curl;
        int carry = 0;
        int num;
        while (curs != null) {
            num = curl.sum + curs.sum + carry;
            carry = num / 10;
            curl.sum = num % 10;
            last = curl;
            curl = curl.next;
            curs = curs.next;
        }
        while (curl != null) {
            num = curl.sum + carry;
            curl.sum = num % 10;
            carry = num / 10;
            last = curl;
            curl = curl.next;
        }
        if (carry != 0) {
            node f = new node(1);
            last.next = f;
        }
        return l;
    }

    public static int countLength(node node) {
        int count = 0;
        while (node != null) {
            node = node.next;
            count++;
        }
        return count;
    }

    public static void main(String[] args) {
        node a1 = new node(8);
        node a2 = new node(7);
        node a3 = new node(3);
        node a4 = new node(2);
        a1.next = a2;
        a2.next = a3;
        a3.next = a4;
        node b1 = new node(4);
        node b2 = new node(3);
        b1.next = b2;
        node c1 = AddTowNumber(a1,b1);
        print(c1);
    }
}
